'use strict';
 
const fs = require('fs');
const path = require('path');
const log4js = require('log4js');
const dayjs = require('dayjs');
const config = require('../config');
 
// 这个是判断是否有logs目录，没有就新建，用来存放日志
const logsDir = config.logger.path;
if (!fs.existsSync(logsDir)) {
  fs.mkdirSync(logsDir);
}
const logPath = path.join(logsDir, `output${dayjs().format('YYYYMM')}.log`);
// 配置log4.js
log4js.configure({
  appenders: {
    console: { type: 'console' },
    dateFile: { type: 'dateFile', filename: logPath, pattern: '' }
  },
  categories: {
    default: {
      appenders: ['console', 'dateFile'],
      level: config.logger.level
    }
  }
});
 
const logger = log4js.getLogger('[Default]');
// logger中间件
const loggerMiddleware = async (ctx, next) => {
  if (ctx.path.includes('swagger')) {
    return await next();
  }
  ctx.logger = logger;
  // 请求开始时间
  const start = new Date();
  let data = await next();
  // 结束时间
  const ms = new Date() - start;
  // 打印出请求相关参数
  const remoteAddress = ctx.headers['x-forwarded-for'] || ctx.ip || ctx.ips ||
    (ctx.socket && (ctx.socket.remoteAddress || (ctx.socket.socket && ctx.socket.socket.remoteAddress)));
  let logText = `${ctx.method} ${ctx.status} ${ctx.url} 请求参数： ${JSON.stringify(ctx.request.body) || '无'} 响应参数： ${JSON.stringify(ctx.body) || '无'} - ${remoteAddress} - ${ms}ms`;
  logger.info(logText);
  return data;
};
module.exports = {
  logger,
  loggerMiddleware
};